package com.eastfair.venuebooking.service.impl;

//import com.baomidou.dynamic.datasource.annotation.DS;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.venuebooking.dao.ExhibitionMapper;
import com.eastfair.venuebooking.entity.Exhibition;
import com.eastfair.venuebooking.service.ExhibitionExportService;
import com.eastfair.venuebooking.service.ExhibitionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.logging.log4j.util.Strings;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 业务实现类
 * 展会
 * </p>
 *
 * @author linan
 * @date 2022-06-08
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class ExhibitionExportServiceImpl extends SuperServiceImpl<ExhibitionMapper, Exhibition> implements ExhibitionExportService {

    @Resource
    private ExhibitionService exhibitionService;
    @Override
    public void exportCoordinationBook(Long exhibitionId, LocalDate date, HttpServletResponse response) {
        try{
            if (Objects.isNull(date)) {
                date = LocalDate.now();
            }
            Exhibition exhibition = this.getById(exhibitionId);
            Map<String, Object> getCoordinationBookView = exhibitionService.getCoordinationBookView(exhibitionId,date, exhibition, new HashMap<>(8));
            List<String> mainInCharge = (List<String>) getCoordinationBookView.get("mainInCharge");
            List<String> assistingStaff = (List<String>) getCoordinationBookView.get("assistingStaff");
            List<Map<String, Object>> exhibitionSegmentList = (List<Map<String, Object>>) getCoordinationBookView.get("exhibitionSegment");
            String mainInChargeName = CollectionUtils.isNotEmpty(mainInCharge)?mainInCharge.get(0): Strings.EMPTY;
            StringBuilder assistingStaffSb=new StringBuilder();
            assistingStaffSb.append(mainInChargeName);
            for (String s : assistingStaff) {
                assistingStaffSb.append(",").append(s);
            }
            String assistingStaffName=assistingStaffSb.toString();
            //创建word文档对象
            XWPFDocument document = new XWPFDocument();
            //这行代码是创建标题
            XWPFParagraph title = document.createParagraph();
            //设置段落居中
            title.setAlignment(ParagraphAlignment.valueOf(STJc.INT_CENTER));
            XWPFRun titleRun = title.createRun();
            titleRun.setFontSize(16);
            titleRun.setFontFamily("黑体");
            titleRun.setBold(true);
            // 展会名称
            titleRun.setText(getCoordinationBookView.get("exhibitionName").toString());
            titleRun.addBreak();

            //添加第一个段落
            XWPFParagraph paragraph1 = document.createParagraph();
            //设置之段落左对齐
            paragraph1.setAlignment(ParagraphAlignment.valueOf(STJc.INT_LEFT));

            String customerNameTitle="  客户名称： ";
            String customerName=getCoordinationBookView.get("customerName").toString();
            int size1=36-String.format("%s%s", customerNameTitle, customerName).length();
            String dateTitle="  日    期： ";
            int size2= size1+2*(customerName.length()-5);
            // ---------以上是设置整段的，以下为设置内容
            XWPFRun firstRun = paragraph1.createRun();
            firstRun.setFontSize(10);
            firstRun.setFontFamily("宋体");
            firstRun.setText(customerNameTitle);
            XWPFRun firstRun2 = paragraph1.createRun();
            firstRun2.setFontSize(10);
            firstRun2.setFontFamily("宋体");
            firstRun2.setText(customerName);
            firstRun2.setUnderline(UnderlinePatterns.SINGLE);
            XWPFRun firstRun3 = paragraph1.createRun();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < size1; i++) {
                sb.append(" ");
            }
            sb.append("负责人员： ");
            firstRun3.setFontSize(10);
            firstRun3.setFontFamily("宋体");
            firstRun3.setText(sb.toString());
            XWPFRun firstRun4 = paragraph1.createRun();
            firstRun4.setFontSize(10);
            firstRun4.setFontFamily("宋体");
            firstRun4.setText(mainInCharge.get(0));
            firstRun4.setUnderline(UnderlinePatterns.SINGLE);
            firstRun4.addBreak();
            firstRun4.addBreak();
            // 第二行
            XWPFRun firstRunTwo = paragraph1.createRun();
            firstRunTwo.setFontSize(10);
            firstRunTwo.setFontFamily("宋体");
            firstRunTwo.setText(dateTitle);
            XWPFRun firstRunTwo2 = paragraph1.createRun();
            firstRunTwo2.setFontSize(10);
            firstRunTwo2.setFontFamily("宋体");
            firstRunTwo2.setText(date.toString());
            firstRunTwo2.setUnderline(UnderlinePatterns.SINGLE);
            XWPFRun firstRunTwo3 = paragraph1.createRun();
            StringBuilder sb2 = new StringBuilder();
            for (int i = 0; i < size2; i++) {
                sb2.append(" ");
            }
            sb2.append("参与人员： ");
            firstRunTwo3.setFontSize(10);
            firstRunTwo3.setFontFamily("宋体");
            firstRunTwo3.setText(sb2.toString());
            XWPFRun firstRunTwo4 = paragraph1.createRun();
            firstRunTwo4.setFontSize(10);
            firstRunTwo4.setFontFamily("宋体");
            firstRunTwo4.setText(assistingStaffName);
            firstRunTwo4.setUnderline(UnderlinePatterns.SINGLE);
            firstRunTwo4.addBreak();

            //创建表格的第一步
            //7为列数，自行调整
            XWPFTable table = document.createTable(1,7);
            CTTbl tTbl = table.getCTTbl();
            CTTblPr tTblPr = tTbl.getTblPr() == null ? tTbl.addNewTblPr() : tTbl.getTblPr();
            CTTblWidth tTblWidth = tTblPr.isSetTblW() ? tTblPr.getTblW() : tTblPr.getTblW();
            //这个宽度是整个大表格的,不是局部或具体的单独大小，注意
            tTblWidth.setW(new BigInteger("10000"));
            tTblWidth.setType(STTblWidth.DXA);
            table.setTableAlignment(TableRowAlign.valueOf(STJc.INT_CENTER));

            //设置表头
            table.getRow(0).setHeight(500);
            setCellText(table.getRow(0).getCell(0),"序号","f5f5f5",400);
            setCellText(table.getRow(0).getCell(1),"环节名称","f5f5f5",1500);
            setCellText(table.getRow(0).getCell(2),"任务名称","f5f5f5",1400);
            setCellText(table.getRow(0).getCell(3),"开始时间","f5f5f5",1400);
            setCellText(table.getRow(0).getCell(4),"结束时间","f5f5f5",1400);
            setCellText(table.getRow(0).getCell(5),"服务部门","f5f5f5",1400);
            setCellText(table.getRow(0).getCell(6),"负责人员","f5f5f5",1400);
            Integer j = 0;
            Integer k = 0;
            for (Map<String, Object> map : exhibitionSegmentList) {
                // 环节名称
                String segmentName = map.get("segmentName").toString();
                // 环节任务
                List<Map<String, Object>> taskList = (List<Map<String, Object>>)map.get("task");
                k = k+1;
                for (int i = 0; i < taskList.size(); i++) {
                    //这个是在表格的添加,添加到第几行
                    XWPFTableRow row = table.insertNewTableRow(j+1);
                    //设置单元格高
                    row.setHeight(500);
                    Map<String, Object> task = taskList.get(i);
                    j = j + 1;
                    if (i == 0) {
                        String text=k.toString();
                        // 序号
                        setCell(row, text,400);
                        // 环节名称
                        setCell(row, segmentName,1500);
                    }else {
                        // 序号
                        setCell(row, Strings.EMPTY,400);
                        // 环节名称
                        setCell(row, Strings.EMPTY,1500);
                    }
                    // 任务名称
                    setCell(row, task.get("taskName").toString(),1400);
                    // 开始时间
                    setCell(row, task.get("startTime").toString(),1400);
                    // 结束时间
                    setCell(row, task.get("endTime").toString(),1400);
                    // 服务部门
                    setCell(row, task.get("orgName").toString(),1400);
                    // 负责人员
                    setCell(row, task.get("responsibleUserName").toString(),1400);
                }
                if(taskList.size()>1){
                    mergeCellsVertically(table,0,j-taskList.size()+1,j);
                    mergeCellsVertically(table,1,j-taskList.size()+1,j);
                }
            }
            //清空缓存
            response.reset();
            // 定义浏览器响应表头，并定义下载名
            String fileName = URLEncoder.encode("统筹书.docx", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+fileName);
            //定义下载的类型，标明是word文件
            response.setContentType("application/msword;charset=UTF-8");
            ServletOutputStream outputStream = response.getOutputStream();
            document.write(outputStream);
            document.close();
        }catch (Exception e){
            log.error("文件导出失败",e);
        }
    }
    private void setCell(XWPFTableRow row, String text,Integer wInt) {
        XWPFTableCell cell = row.createCell();
        XWPFParagraph cellParagraph = cell.getParagraphArray(0);
        cellParagraph.setAlignment(ParagraphAlignment.CENTER);
        CTTc ctTc = cell.getCTTc();
        CTTcPr ctTcPr = ctTc.addNewTcPr();
        ctTcPr.addNewTcW().setW(BigInteger.valueOf(wInt));
        cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
        ctTcPr.addNewVAlign().setVal(STVerticalJc.CENTER);
        cell.setText(text);
    }

    // 设置表头 参数
    private static void  setCellText(XWPFTableCell cell, String text, String bgcolor, Integer width){
        CTTc ctTc = cell.getCTTc();
        CTTcPr ctTcPr = ctTc.addNewTcPr();
        ctTcPr.addNewTcW().setW(BigInteger.valueOf(width));
        cell.getCTTc().addNewTcPr().addNewShd().setFill(bgcolor);
        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
        CTTcPr ctPr = ctTc.addNewTcPr();
        ctPr.addNewVAlign().setVal(STVerticalJc.CENTER);
        CTP ctp = ctTc.getPList().get(0);
        CTPPr ctppr = ctp.getPPr();
        if (ctppr == null) {
            ctppr = ctp.addNewPPr();
        }
        CTJc ctjc = ctppr.getJc();
        if (ctjc == null) {
            ctjc = ctppr.addNewJc();
        }
        //水平居中
        ctjc.setVal(STJc.CENTER);
        cell.setText(text);
    }
    /**
     * @Description: 跨行合并
     * table要合并单元格的表格
     * col要合并哪一列的单元格
     * fromRow从哪一行开始合并单元格
     * toRow合并到哪一个行
     */
    public  void mergeCellsVertically(XWPFTable table, int col, int fromRow, int toRow) {
        for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
            XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
            if ( rowIndex == fromRow ) {
                // The first merged cell is set with RESTART merge value
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
            } else {
                // Cells which join (merge) the first one, are set with CONTINUE
                cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

    /**
     * @Description: 跨列合并
     * table要合并单元格的表格
     * row要合并哪一行的单元格
     * fromCell开始合并的单元格
     * toCell合并到哪一个单元格
     */
    public  void mergeCellsHorizontal(XWPFTable table, int row, int fromCell, int toCell) {
        for (int cellIndex = fromCell; cellIndex <= toCell; cellIndex++) {
            XWPFTableCell cell = table.getRow(row).getCell(cellIndex);
            if ( cellIndex == fromCell ) {
                // The first merged cell is set with RESTART merge value
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
            } else {
                // Cells which join (merge) the first one, are set with CONTINUE
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
            }
        }
    }
}
